package com.hulk.dryad.manage.security.listener;

import com.hulk.dryad.manage.security.handler.AuthenticationFailureEventHandler;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.auto.annotation.AutoListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationFailureProviderNotFoundEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hulk
 * @date 2020/03/25 认证失败事件监听器
 */
@Component
@AutoListener
@RequiredArgsConstructor
public class AuthenticationFailureEventListener implements ApplicationListener<AbstractAuthenticationFailureEvent> {

	private final ObjectProvider<AuthenticationFailureEventHandler> dryadAuthenticationFailureEventHandler;

	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	@Override
	public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
		// 此类型事件不传递处理
		if (event instanceof AuthenticationFailureProviderNotFoundEvent) {
			return;
		}
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		HttpServletResponse response = requestAttributes.getResponse();

		AuthenticationException authenticationException = event.getException();
		Authentication authentication = (Authentication) event.getSource();
		AuthenticationFailureEventHandler handler =	dryadAuthenticationFailureEventHandler.getIfAvailable();
		// 调用自定义业务实现
		if (handler != null) {
			handler.handle(authenticationException, authentication, request, response);
		}
	}

}
